﻿using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.物料管理
{
	public partial class MaterialInfoForm : CCSkinMain
	{
		public MaterialInfoForm()
		{
			InitializeComponent();
			this.Load += MaterialInfoForm_Load;
			InitializeOutboundGrid();
		}

		private async void MaterialInfoForm_Load(object sender, EventArgs e)
		{
			await QueryAndBindAsync();
			await BindPickingAsync();
        }

		private async void btnSearch_Click(object sender, EventArgs e)
		{
			await QueryAndBindAsync();
		}

		private async Task QueryAndBindAsync()
		{
			string baseUrl = "http://localhost:5128/api/Material/GetMaterialInfo?PickState=true";
			string materialCode = txtMaterialCode != null ? txtMaterialCode.Text?.Trim() : string.Empty;
			if (!string.IsNullOrEmpty(materialCode))
			{
				baseUrl += $"?MaterialCode={Uri.EscapeDataString(materialCode)}";
			}

			using (HttpClient client = new HttpClient())
			{
				try
				{
					HttpResponseMessage response = await client.GetAsync(baseUrl);
					response.EnsureSuccessStatusCode();
					string jsonResponse = await response.Content.ReadAsStringAsync();
					MaterialApiResponse<MaterialInfoDto> apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<MaterialInfoDto>>(jsonResponse);
					if (apiResponse != null && apiResponse.code == 200)
					{
						var list = apiResponse.data;
						dgvMaterialInfo.AutoGenerateColumns = false;
						dgvMaterialInfo.DataSource = list;
					}
					else
					{
						MessageBox.Show($"查询失败{apiResponse?.message}");
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show($"请求失败: {ex.Message}");
				}
			}
		}

		/// <summary>
		/// 初始化领料单列表，添加删除操作列
		/// </summary>
		private void InitializeOutboundGrid()
		{
			if (dgvPinkingInfo == null) return;
			// 只添加一次
			if (!dgvPinkingInfo.Columns.Contains("Delete"))
			{
				var col = new DataGridViewButtonColumn
				{
					Name = "Delete",
					HeaderText = "删除",
					Text = "删除",
					UseColumnTextForButtonValue = true,
					Width = 70
				};
				dgvPinkingInfo.Columns.Add(col);
			}
			// 绑定单击事件
			dgvPinkingInfo.CellClick -= dgvPinkingInfo_CellClick;
			dgvPinkingInfo.CellClick += dgvPinkingInfo_CellClick;
		}

		/// <summary>
		/// 处理删除按钮点击
		/// </summary>
		private async void dgvPinkingInfo_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0) return;
			if (!dgvPinkingInfo.Columns.Contains("Delete")) return;
			if (e.ColumnIndex != dgvPinkingInfo.Columns["Delete"].Index) return;

			var dto = dgvPinkingInfo.Rows[e.RowIndex].DataBoundItem as PinkingInfoDto;
			if (dto == null) return;
			int id = dto.outboundId;
			if (id <= 0)
			{
				MessageBox.Show("未获取到要删除的记录ID(OutboundId)");
				return;
			}

			if (MessageBox.Show("确定要删除该领料单记录吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				await DeleteOutboundAsync(id);
			}
		}

		/// <summary>
		/// 调用后端删除接口
		/// </summary>
		private async Task DeleteOutboundAsync(int id)
		{
			string url = $"http://localhost:5128/api/Pinking/DelOutboundRecord?Id={id}";
			using (HttpClient client = new HttpClient())
			{
				try
				{
					var resp = await client.GetAsync(url);
					if (resp.IsSuccessStatusCode)
					{
						MessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
						await BindPickingAsync();
					}
					else
					{
						string body = await resp.Content.ReadAsStringAsync();
						MessageBox.Show($"删除失败: {resp.StatusCode} {body}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show($"删除发生异常: {ex.Message}");
				}
			}
		}

        private void dgvMaterialInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
			string materialCode = dgvMaterialInfo.Rows[e.RowIndex].Cells["物料编号"].Value.ToString();

        }

        private void btnMaterialInfo_Click(object sender, EventArgs e)
        {

        }
        private async Task BindPickingAsync()
        {
            string baseUrl = "http://localhost:5128/api/Material/GetOutboundRecord";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    MaterialApiResponse<PinkingInfoDto> apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<PinkingInfoDto>>(jsonResponse);
                    if (apiResponse.code == 200)
                    {
                        dgvPinkingInfo.AutoGenerateColumns = false;
                        dgvPinkingInfo.DataSource = apiResponse.data;
                    }
                    else
                    {
                        MessageBox.Show($"查询失败{apiResponse?.message}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }
            }
        }
    }
}
